import { useState, forwardRef, useImperativeHandle, useEffect } from 'react';
import './index.scss';

type PropsData = {};

const Toast = forwardRef<ToastRef, PropsData>((props, ref) => {
  const [content, setContent] = useState('');
  const [show, setShow] = useState(false);

  useEffect(() => {
    let timer: any = null;
    if (show) {
      timer = setTimeout(() => {
        setContent('');
        setShow(false);
      }, 1500);
    }
    return () => {
      clearTimeout(timer);
    };
  }, [show]);

  useImperativeHandle(ref, () => ({
    showToast: (v: string) => {
      setContent(v);
      setShow(true);
    },
    hideToast: () => {
      setContent('');
      setShow(false);
    },
  }));

  return (
    <>
      {show && (
        <div className='toast-view'>
          <div className='toast-txt'>{content}</div>
        </div>
      )}
    </>
  );
});

export default Toast;
